import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { CreateUserDto } from './dto/create-user.dto';
import { User, UserDocument } from './schemas/user.schema';

@Injectable()
export class UsersService {
  constructor(@InjectModel(User.name) private userModel: Model<UserDocument>) {}

  /**
   * 创建一个用户
   * @param createUserDto 要创建的用户
   * @returns 创建好的用户
   */
  async create(createUserDto: CreateUserDto): Promise<UserDocument> {
    const createdCat = new this.userModel(createUserDto);
    return createdCat.save();
  }

  /**
   * 查询所有用户
   * @returns 所有用户
   */
  async findAll(): Promise<User[]> {
    return this.userModel.find({}, 'nickName').exec();
  }

  /**
   * 通过微信用户唯一标识查找用户，若不存在则创建一个
   * @param openid 微信用户唯一标识
   * @returns 一个用户对象
   */
  async findOneByOpenid(openid: string): Promise<UserDocument> {
    let user = await this.userModel.findOne({ openid }, '_id').exec();

    if (user === null) {
      user = await this.create({ openid });
    }

    return user;
  }
}
